<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .success { color: #28a745; }
        .error { color: #dc3545; }
        .warning { color: #ffc107; }
        .info { color: #17a2b8; }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background: #0056b3; }
        button:disabled { background: #6c757d; cursor: not-allowed; }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            margin: 10px 0;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        input, select {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        .form-group {
            margin: 10px 0;
        }
        .form-group label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 API调试工具</h1>
        
        <div class="form-group">
            <label>API地址:</label>
            <input type="text" id="apiUrl" value="http://localhost:8080/api" style="width: 300px;">
        </div>
        
        <div class="form-group">
            <label>Token:</label>
            <input type="text" id="token" placeholder="JWT Token" style="width: 400px;">
            <button onclick="getTokenFromStorage()">从存储获取</button>
        </div>
    </div>

    <div class="container">
        <h3>1. 认证测试</h3>
        <div class="form-group">
            <label>用户名:</label>
            <input type="text" id="username" value="agent1">
        </div>
        <div class="form-group">
            <label>密码:</label>
            <input type="password" id="password" value="agent123">
        </div>
        <button onclick="testLogin()">测试登录</button>
        <div id="loginResult" class="log"></div>
    </div>

    <div class="container">
        <h3>2. 工单API测试</h3>
        <button onclick="testTicketsList()">测试工单列表</button>
        <button onclick="testTicketCreate()">测试创建工单</button>
        <div id="ticketsResult" class="log"></div>
    </div>

    <div class="container">
        <h3>3. Token管理</h3>
        <button onclick="checkToken()">检查Token</button>
        <button onclick="clearToken()">清除Token</button>
        <button onclick="refreshToken()">刷新Token</button>
        <div id="tokenResult" class="log"></div>
    </div>

    <div class="container">
        <h3>4. 网络诊断</h3>
        <button onclick="testConnection()">测试连接</button>
        <button onclick="testCORS()">测试CORS</button>
        <div id="networkResult" class="log"></div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:8080/api';
        
        function log(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            const timestamp = new Date().toLocaleTimeString();
            const className = type === 'error' ? 'error' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'info';
            element.innerHTML += `<span class="${className}">[${timestamp}] ${message}</span>\n`;
            element.scrollTop = element.scrollHeight;
        }

        function clearLog(elementId) {
            document.getElementById(elementId).innerHTML = '';
        }

        function getTokenFromStorage() {
            const token = localStorage.getItem('token');
            if (token) {
                document.getElementById('token').value = token;
                log('tokenResult', '✅ 从存储获取Token成功', 'success');
            } else {
                log('tokenResult', '❌ 存储中没有Token', 'error');
            }
        }

        async function testLogin() {
            clearLog('loginResult');
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            log('loginResult', `测试登录: ${username}`, 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password }),
                    mode: 'cors'
                });

                log('loginResult', `响应状态: ${response.status}`, 'info');
                
                const data = await response.json();
                log('loginResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                
                if (response.ok && data.code === 0) {
                    log('loginResult', '✅ 登录成功', 'success');
                    if (data.data && data.data.token) {
                        document.getElementById('token').value = data.data.token;
                        log('loginResult', '✅ Token已设置到输入框', 'success');
                    }
                } else {
                    log('loginResult', `❌ 登录失败: ${data.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                log('loginResult', `❌ 请求失败: ${error.message}`, 'error');
            }
        }

        async function testTicketsList() {
            clearLog('ticketsResult');
            const token = document.getElementById('token').value;
            
            if (!token) {
                log('ticketsResult', '❌ 请先设置Token', 'error');
                return;
            }
            
            log('ticketsResult', '测试工单列表API...', 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/tickets`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    mode: 'cors'
                });

                log('ticketsResult', `响应状态: ${response.status}`, 'info');
                
                if (response.ok) {
                    const data = await response.json();
                    log('ticketsResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                    log('ticketsResult', '✅ 工单列表获取成功', 'success');
                } else {
                    const errorData = await response.text();
                    log('ticketsResult', `❌ 请求失败: ${errorData}`, 'error');
                }
            } catch (error) {
                log('ticketsResult', `❌ 请求失败: ${error.message}`, 'error');
            }
        }

        async function testTicketCreate() {
            clearLog('ticketsResult');
            const token = document.getElementById('token').value;
            
            if (!token) {
                log('ticketsResult', '❌ 请先设置Token', 'error');
                return;
            }
            
            const ticketData = {
                title: '测试工单',
                description: '这是一个测试工单',
                priority: 'MEDIUM',
                categoryId: 1
            };
            
            log('ticketsResult', '测试创建工单API...', 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/tickets`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(ticketData),
                    mode: 'cors'
                });

                log('ticketsResult', `响应状态: ${response.status}`, 'info');
                
                if (response.ok) {
                    const data = await response.json();
                    log('ticketsResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                    log('ticketsResult', '✅ 工单创建成功', 'success');
                } else {
                    const errorData = await response.text();
                    log('ticketsResult', `❌ 请求失败: ${errorData}`, 'error');
                }
            } catch (error) {
                log('ticketsResult', `❌ 请求失败: ${error.message}`, 'error');
            }
        }

        function checkToken() {
            clearLog('tokenResult');
            const token = document.getElementById('token').value;
            
            if (!token) {
                log('tokenResult', '❌ 没有Token', 'error');
                return;
            }
            
            try {
                const parts = token.split('.');
                if (parts.length !== 3) {
                    log('tokenResult', '❌ Token格式错误', 'error');
                    return;
                }
                
                const payload = JSON.parse(atob(parts[1]));
                const now = Math.floor(Date.now() / 1000);
                
                log('tokenResult', `用户ID: ${payload.userId}`, 'info');
                log('tokenResult', `用户名: ${payload.username}`, 'info');
                log('tokenResult', `角色: ${payload.role}`, 'info');
                log('tokenResult', `签发时间: ${new Date(payload.iat * 1000).toLocaleString()}`, 'info');
                log('tokenResult', `过期时间: ${new Date(payload.exp * 1000).toLocaleString()}`, 'info');
                
                if (payload.exp && payload.exp < now) {
                    log('tokenResult', '❌ Token已过期', 'error');
                } else {
                    log('tokenResult', '✅ Token有效', 'success');
                }
            } catch (error) {
                log('tokenResult', `❌ Token解析失败: ${error.message}`, 'error');
            }
        }

        function clearToken() {
            document.getElementById('token').value = '';
            localStorage.removeItem('token');
            localStorage.removeItem('user_info');
            log('tokenResult', '✅ Token已清除', 'success');
        }

        async function refreshToken() {
            clearLog('tokenResult');
            const token = document.getElementById('token').value;
            
            if (!token) {
                log('tokenResult', '❌ 请先设置Token', 'error');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/refresh`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    mode: 'cors'
                });

                log('tokenResult', `响应状态: ${response.status}`, 'info');
                
                if (response.ok) {
                    const data = await response.json();
                    log('tokenResult', `响应数据: ${JSON.stringify(data, null, 2)}`, 'info');
                    
                    if (data.code === 0 && data.data && data.data.token) {
                        document.getElementById('token').value = data.data.token;
                        log('tokenResult', '✅ Token刷新成功', 'success');
                    } else {
                        log('tokenResult', '❌ Token刷新失败', 'error');
                    }
                } else {
                    log('tokenResult', '❌ Token刷新请求失败', 'error');
                }
            } catch (error) {
                log('tokenResult', `❌ 请求失败: ${error.message}`, 'error');
            }
        }

        async function testConnection() {
            clearLog('networkResult');
            log('networkResult', '测试后端连接...', 'info');
            
            try {
                const response = await fetch('http://localhost:8080/', {
                    method: 'HEAD',
                    mode: 'cors'
                });
                
                if (response.ok) {
                    log('networkResult', '✅ 后端服务运行正常', 'success');
                } else {
                    log('networkResult', `⚠️ 后端响应异常: ${response.status}`, 'warning');
                }
            } catch (error) {
                log('networkResult', `❌ 连接失败: ${error.message}`, 'error');
                log('networkResult', '可能原因:', 'warning');
                log('networkResult', '1. 后端服务未启动', 'warning');
                log('networkResult', '2. 端口8080被占用', 'warning');
                log('networkResult', '3. CORS配置问题', 'warning');
            }
        }

        async function testCORS() {
            clearLog('networkResult');
            log('networkResult', '测试CORS配置...', 'info');
            
            try {
                const response = await fetch(`${API_BASE_URL}/auth/login`, {
                    method: 'OPTIONS',
                    headers: {
                        'Access-Control-Request-Method': 'POST',
                        'Access-Control-Request-Headers': 'Content-Type'
                    },
                    mode: 'cors'
                });
                
                if (response.ok) {
                    log('networkResult', '✅ CORS预检请求成功', 'success');
                } else {
                    log('networkResult', `⚠️ CORS预检请求失败: ${response.status}`, 'warning');
                }
            } catch (error) {
                log('networkResult', `❌ CORS测试失败: ${error.message}`, 'error');
            }
        }

        // 页面加载时自动获取Token
        window.onload = function() {
            getTokenFromStorage();
            testConnection();
        };
    </script>
</body>
</html>
